package com.shijie99.demo.controller;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shijie99.demo.pojo.ConfigCookie;
import com.shijie99.demo.pojo.ConfigCookieExample;
import com.shijie99.demo.pojo.ConfigUser;
import com.shijie99.demo.pojo.ConfigUserExample;
import com.shijie99.demo.service.UserService;
import com.shijie99.demo.util.Constant;

@Controller
public class LoginController {
	private static final String LOGIN_PAGE = "login";
	
	private static final String INDEX_PAGE = "main/index";
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = {"/", "/index", "index.html", "index.html", "index.jsp"}, method = RequestMethod.GET) 
	public String index(HttpServletRequest request, HttpServletResponse response) {
		String page = login(request, response);
		return page;
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response) {
		ConfigUser user = (ConfigUser)request.getSession().getAttribute(Constant.SESSION_USER);
		if(user != null) {
			return INDEX_PAGE;
		} 
		
		String cookieData = null;
		Cookie[] cookies = request.getCookies();
		if(cookies != null) {
			for(Cookie cookie : cookies) {
				if(cookie.getName().equals(Constant.COOKIE_KEY)) {
					cookieData = cookie.getValue();
					break;
				}
			}
			
			if(cookieData != null) {
				JSONObject jsonbObj = JSON.parseObject(cookieData);
				String jsessionId = jsonbObj.getString(Constant.COOKIE_JSON_KEY) == null ? 
						"" : jsonbObj.getString(Constant.COOKIE_JSON_KEY);
				
				//根据jsessionid查找数据库中是否设置了对应的jsessionid
				ConfigCookieExample example = new ConfigCookieExample();
				example.createCriteria().andJsessionidEqualTo(jsessionId);
				ConfigCookie cookie = userService.selectConfigCookieByExample(example);
				
				if(cookie != null) {
					user = userService.selectConfigUserByPriamryKey(cookie.getUid());
					request.getSession().setAttribute(Constant.SESSION_USER, user);
					
					return INDEX_PAGE;
				} else {
					return LOGIN_PAGE;
				}
			} else {
				return LOGIN_PAGE;
			}
		} else {
			return LOGIN_PAGE;
		}
	}
	
	@RequestMapping(value = "/login.ajax", method = RequestMethod.POST)
	public void loginAjax(String username, String password, String rememberme, 
			HttpServletRequest request, HttpServletResponse response) {
		ConfigUserExample example = new ConfigUserExample();
		example.createCriteria()
			   .andUsernameEqualTo(username)
			   .andPasswordEqualTo(password);
				
		ConfigUser user = userService.authConfigUserByExample(example);
		
		JSONObject retObj = new JSONObject();
		
		if(user != null) {
			//验证用户名和密码成功，根据rememberme参数，是否存储数据库和写入cookie
			if(rememberme.equals("1")) {
				String jsessionid = UUID.randomUUID().toString();
				
				//存入userid和jsessionid
				ConfigCookie configCookie = new ConfigCookie();
				configCookie.setJsessionid(jsessionid);
				configCookie.setUid(user.getId());
				userService.insertConfigCookie(configCookie);
				
				//写入客户端cookie
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(Constant.COOKIE_JSON_KEY, jsessionid);
				Cookie cookie = new Cookie("whitelist.shijie99.com", 
						jsonObject.toString());
				
				cookie.setPath("/WhiteListController");
				cookie.setMaxAge(36000);
				response.addCookie(cookie);
			}
			
			//写入session
			request.getSession().setAttribute(Constant.SESSION_USER, user);
			
			//返回json对象填充
			retObj.put("permission", "1");
		} else {
			retObj.put("permission", "0");
		}
		
		try {
			response.getWriter().write(retObj.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		//撤销session
		request.getSession().removeAttribute(Constant.SESSION_USER);
		
		Cookie[] cookies = request.getCookies();
		String cookieData = null;
		if(cookies != null) {
			for(Cookie cookie : cookies) {
				if(cookie.getName().equals(Constant.COOKIE_KEY)) {
					cookieData = cookie.getValue();
					
					//删除客户端cookie
					cookie.setMaxAge(0);
					response.addCookie(cookie);
					break;
				}
			}
			
			if(cookieData != null) {
				//删除服务器的cookie值记录
				String jsessionid = JSON.parseObject(cookieData).get(Constant.COOKIE_JSON_KEY).toString();
				
				//
				ConfigCookieExample example = new ConfigCookieExample();
				example.createCriteria()
					   .andJsessionidEqualTo(jsessionid);
				
				userService.deleteConfigCookieByExample(example);
			}
		}
		
		return "login";
	}
}
